/*
    Copyright 2011 Anishek Agarwal(anishek@gmail.com), Ashish Mishra(ashish@ashishmishra.in)
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

package com.thoughtworks.ant;

import java.io.StringWriter;
import java.util.*;

public class Store<K, V> {

    private Map<K, List<V>> map = new HashMap<K, List<V>>();

    public boolean put(K key, V value) {
        if (map.containsKey(key)) {
            return map.get(key).add(value);
        }
        ArrayList<V> list = new ArrayList<V>();
        list.add(value);
        map.put(key, list);
        return true;
    }

    public boolean putAll(K key, List<V> values) {
        if (map.containsKey(key)) {
            return map.get(key).addAll(values);
        }
        ArrayList<V> list = new ArrayList<V>();
        list.addAll(values);
        map.put(key, list);
        return true;
    }


    public List<V> get(K key) {
        return map.get(key);
    }

    public Set<K> keySet() {
        return map.keySet();
    }

    public boolean hasDuplicates(K key) {
        return map.containsKey(key) && map.get(key).size() > 1;
    }

    public int size() {
        return map.size();
    }

    public boolean isEmpty() {
        return map.isEmpty();
    }

    @Override
    public String toString() {
        StringWriter writer = new StringWriter();
        for (Map.Entry<K, List<V>> entry : map.entrySet()) {
            writer.append(entry.getKey() + " in " + entry.getValue() + "\n");
        }
        return writer.toString();
    }
}
